import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartitem:JSON.parse(localStorage.getItem("cart"))||[],
    totalPrice:0
  },
  mutations: {
    getcartlist(state,item){
      var index=state.cartitem.findIndex((ele)=>{
        return  ele.id===item.id
      })
      if(index!=-1){
        state.cartitem[index].count++
      }else{
        item.count=0;
        state.cartitem.push(item)
      }
      item.count++
      state.totalPrice=0
      state.cartitem.forEach((ele)=>{
        state.totalPrice+=ele.count*ele.comm_price
      })
      localStorage.setItem("cart",JSON.stringify(state.cartitem))
      // console.log(state.cartitem)

    },
    addcount(state,item){
        state.cartitem.forEach((ele)=>{
          return ele.id===item.id
        })
        
        item.count++
        state.totalPrice=0
        state.cartitem.forEach((ele)=>{
          state.totalPrice+=ele.count*ele.comm_price
        })
        localStorage.setItem("cart",JSON.stringify(state.cartitem))
    },
    minuscount(state,item){
      state.cartitem.forEach((ele)=>{
        return ele.id===item.id
      })
      if(item.count===1){
        item.count=1;
        return
      }
      item.count--
      state.totalPrice=0
      state.cartitem.forEach((ele)=>{
        state.totalPrice+=ele.count*ele.comm_price
      })
      localStorage.setItem("cart",JSON.stringify(state.cartitem))
    },
    deleall(state){
      state.cartitem=[]
      state.totalPrice=0
      localStorage.setItem("cart",JSON.stringify(state.cartitem))
    }
  },
  actions: {
    getcartlist(context,item){
      // console.log(item)
      context.commit("getcartlist",item)
    },
    addcount(context,item){
      context.commit("addcount",item)
    },
    minuscount(context,item){
      context.commit("minuscount",item)
    },
    deleall(context){
      context.commit("deleall")
    }
  },
  modules: {
  }
})
